<?php

namespace App\Http\Controllers\Backstage\System;

use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\BaseImgService;
use App\Services\CityService;
use Illuminate\Validation\Rule;
use App\BaseImg;

class BaseImageController extends Controller
{
    private $baseImgService = null;
    private $cityService = null;

    public function __construct(BaseImgService $baseImgService,
        CityService $cityService)
    {
        $this->baseImgService = $baseImgService;
        $this->cityService = $cityService;
    }

    public function index()
    {
        return view('backstage.system.baseimg.baseimage', [
            'allcities' => $this->cityService->getAllCities()
        ]);
    }

    public function getImages(Request $request)
    {
        return $this->baseImgService
            ->getBaseImages($request->all());
    }

    public function create()
    {
        return view('backstage.system.baseimg.create_image', [
            'allcities' => $this->cityService->getAllCities()
        ]);
    }

    public function saveNew(Request $request)
    {
        $input = $request->all();

        $this->validateWhenSaveNew($input);

        if ($input['city_id'] == 0) {
            $input['city_id'] = null;
        }
        BaseImg::create($input);

        return response()->json([
            'Success' => true,
            'Message' => '新增图片成功',
        ]);
    }

    private function validateWhenSaveNew(Array $input)
    {
        return Validator::make($input, [
            //基础性验证
            'picture' => 'required|max:200',
            'img_type' => [
                'required',
                Rule::in(BaseImg::getBaseImageTypeKeys())
            ],
            'city_id' => [
                'required',
                Rule::in($this->getIllegalCities())
            ],
            'link_url' => 'max:255',
            'sort_order' => 'required|numeric'
        ], $this->getValidateMessagesWhenSaveNew())->validate();
    }

    private function getValidateMessagesWhenSaveNew() {
        return [
            'picture.required' => '图片必须存在',
            'picture.max'  => '图片地址长度不可超过:max',
            'img_type.required' => '图片类型必须存在',
            'img_type.in' => '图片类型值不合法',
            'city_id.required'  => '城市ID必须存在，所有城市传入0',
            'city_id.in' => '城市ID值不合法',
            'link_url.max' => '图片链接长度不可超过:max',
            'sort_order.required' => '排序号必须存在',
            'sort_order.numeric' => '排序号必须是数字',
        ];
    }

    private function getIllegalCities()
    {
        $cityIds = $this->cityService->getAllCities()->pluck('id')->toArray();

        array_push($cityIds, 0);

        return $cityIds;
    }
}
